<?php
namespace app\admin\controller;

use app\admin\model\RoleModel;
use app\admin\model\UserModel;
use app\admin\model\DepartmentModel;
use app\admin\model\WebsetModel;
use think\Controller;
use org\Verify;
use think\Db;

class Login extends Controller
{
    // 登录页面
    public function index()
    {
		$webset = new WebsetModel();
        $websetInfo = $webset->getInfo();
        DB::name('log')->where('c_time','<',strtotime('-' . $websetInfo['log_expire'] . ' day'))->delete();
		$this->assign([
			'Webset'=>$websetInfo,
            'user_id'=>session('id')
		]);
        return $this->fetch('/login');
    }

    // 登录操作
    public function doLogin()
    {
        $userName = input("param.user_name");
        $password = input("param.password");
        $code = input("param.code");
        $result = $this->validate(compact('userName', 'password', "code"), 'AdminValidate');
        if(true !== $result){
            return json(msg(-1, '', $result));
        }
        $verify = new Verify();
        if (!$verify->check($code)) {
            return json(msg(-2, '', '验证码错误'));
        }
        $userModel = new UserModel();
        $hasUser = $userModel->findUserByName($userName);
        if(empty($hasUser)){
            return json(msg(-3, '', '管理员不存在'));
        }
        if(md5($password . config('salt')) != $hasUser['password']){
            return json(msg(-4, '', '密码错误'));
        }
        if(1 != $hasUser['status']){
            return json(msg(-5, '', '该账号被禁用'));
        }
        // 获取该管理员的角色信息
        $roleModel = new RoleModel();
		$departModel = new DepartmentModel();
        $roleInfo = $roleModel->getRoleInfo($hasUser['role_id']);
		$departName = $departModel->where('id',$hasUser['depart_id'])->value('name');
        session('username', $userName);
        session('id', $hasUser['id']);
        session('head', $hasUser['head']);
        session('role', $roleInfo['role_name']); 		// 角色名
		session('role_id', $hasUser['role_id']);  		// 角色id
		session('depart_name', $departName);  			// 部门名称
		session('depart_id', $hasUser['depart_id']); 	// 部门id
		session('rule', $roleInfo['rule']);  			// 角色节点
        session('action', $roleInfo['action']);  		// 角色权限
		// 设置数据权限
		$this->setDataAuth($hasUser);
        // 更新管理员状态
        $param = [
            'login_times' => $hasUser['login_times'] + 1,
            'last_login_ip' => request()->ip(),
            'last_login_time' => time()
        ];
        $res = $userModel->updateStatus($param, $hasUser['id']);
        if(1 != $res['code']){
            return json(msg(-6, '', $res['msg']));
        }
        return json(msg(1, url('index/index'), '登录成功'));
    }

    // 验证码
    public function checkVerify()
    {
		$fontttfArr = [2,4,6];
		$fontttf = $fontttfArr[array_rand($fontttfArr,1)].".ttf";
        $verify = new Verify();
        $verify->imageH = 32;
        $verify->imageW = 100;
        $verify->length = 4;
        $verify->useNoise = false;
		$verify->useCurve = true;
		$verify->fontttf = $fontttf;
        $verify->fontSize = 14;
        return $verify->entry();
    }

    /**
     * [退出登陆]
     */
    public function loginOut(){
        session('username', null);
        session('id', null);
        session('head', null);
        session('role', null);
        session('rule', null);
        session('action', null);
		session('data_auth', null);
		session('data_auth_type', null);
		session('role_id',null);
		session('depart_name',null);
		session('depart_id',null);
        $this->redirect(url('index'));
    }

	public function setDataAuth($user) {
		session('data_auth_type',$user['data_auth_type']);  // 数据权限类型
		$arr = [];
		$departModel = new DepartmentModel();
		$userModel = new UserModel();
		switch ($user['data_auth_type']) {
			case '0': # 仅自己
				$arr[] = $user['id'];break;
			case '1': # 所有
				$arr = "*";break;
			case '2': # 本部门
				$arr = $userModel->where('depart_id',$user['depart_id'])->column("id");break;
			case '3': # 本部门 及 子部门
				$depart_ids = $departModel->getSonsByPid($user['depart_id']);
				$depart_ids[] = $user['depart_id'];
				$arr = $userModel->where('depart_id','in',$depart_ids)->column("id");
				break;
			default: # 默认仅自己
				$arr[] = $user['id'];break;
		}
		session('data_auth',$arr);
	}
}
